package org.tim.websocket.chat;

import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.tim.common.util.Sessions;
import org.tim.es.message.UserPrivateMessage;
import org.tim.es.message.UserPrivateMessageResource;
import org.tim.es.session.UserPrivareSessionResource;
import org.tim.es.session.UserPrivateSession;
import org.tim.common.msg.MsgType;
import org.tim.common.msg.TimMessage;
import org.tio.core.ChannelContext;
import org.tio.websocket.common.WsResponse;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
public class PrivateTextChatKit implements BeforeChatKit {
    @Autowired
    private UserPrivareSessionResource privareSessionResource;

    @Autowired
    private UserPrivateMessageResource privateMessageResource;

    @Override
    public boolean isSupport(TimMessage timMessage) {
        return MsgType.TEXT.equals(timMessage.getMsgType());
    }

    public void beforeChat(WsResponse wsResponse, TimMessage timMessage, ChannelContext channelContext, Promise<TimMessage> promise) {
        var now = LocalDateTime.now();

        // 重试消息不允许再次进入
        if (Strings.isNotEmpty(timMessage.getId())) {
            return;
        }

        synchronized (this) {
            try {
                var sessionId = Sessions.getSessionId(timMessage.getFromUserId(), timMessage.getToUserId());
                var sessionOptional = privareSessionResource.findById(sessionId);
                if (sessionOptional.isPresent()) {
                    var session = sessionOptional.get();
                    session.setLastSessionAt(now);
                    session.setLaseSessionMessage(timMessage.getContent().toString());
                    session.setUnreadCnt(session.getUnreadCnt() != null ? session.getUnreadCnt() + 1L : 1L);
                    session.setDelete(Boolean.FALSE);
                    privareSessionResource.save(session);
                } else {
                    var userPrivateSession = new UserPrivateSession();
                    userPrivateSession.setId(sessionId);
                    userPrivateSession.setFromUserId(timMessage.getFromUserId());
                    userPrivateSession.setToUserId(timMessage.getToUserId());
                    userPrivateSession.setDelete(Boolean.FALSE);
                    userPrivateSession.setLastSessionAt(now);
                    userPrivateSession.setCreatedAt(now);
                    userPrivateSession.setLaseSessionMessage(timMessage.getContent().toString());
                    userPrivateSession.setUnreadCnt(1L);
                    privareSessionResource.save(userPrivateSession);
                }

                var userPrivateMessage = new UserPrivateMessage();
                userPrivateMessage.setId(UUID.randomUUID().toString());
                userPrivateMessage.setSessionId(sessionId);
                userPrivateMessage.setFromUserId(timMessage.getFromUserId());
                userPrivateMessage.setToUserId(timMessage.getToUserId());
                userPrivateMessage.setMsgType(timMessage.getMsgType());
                userPrivateMessage.setMsgContent(timMessage.getContent());
                userPrivateMessage.setTimMessage(timMessage);
                userPrivateMessage.setSendAt(now);
                UserPrivateMessage save = privateMessageResource.save(userPrivateMessage);
                timMessage.setId(save.getId());
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    }
}
